{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Smoothing trajectories\n",
    "\n",
    "<img align=\"right\" src=\"https://anitagraser.github.io/movingpandas/assets/img/movingpandas.png\">\n",
    "\n",
    "[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/anitagraser/movingpandas-examples/main?filepath=1-tutorials/10-smoothing-trajectories.ipynb)\n",
    "[![IPYNB](https://img.shields.io/badge/view-ipynb-hotpink)](https://github.com/anitagraser/movingpandas-examples/blob/main/1-tutorials/10-smoothing-trajectories.ipynb)\n",
    "[![HTML](https://img.shields.io/badge/view-html-green)](https://anitagraser.github.io/movingpandas-website/1-tutorials/10-smoothing-trajectories.html)\n",
    "\n",
    "To smooth trajectories, we can use a Kalman filter. The implemented KalmanSmootherCV is based on the assumption of a nearly-constant velocity (CV) model. To use KalmanSmootherCV, the optional dependency `StoneSoup` needs to be installed.\n",
    "\n",
    "[Documentation](https://movingpandas.readthedocs.io/en/master/trajectorysmoother.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import geopandas as gpd\n",
    "from geopandas import GeoDataFrame, read_file\n",
    "from shapely.geometry import Point, LineString, Polygon\n",
    "from datetime import datetime, timedelta\n",
    "from matplotlib import pyplot as plt\n",
    "import movingpandas as mpd\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "mpd.show_versions()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gdf = read_file('../data/geolife_small.gpkg')\n",
    "traj_collection = mpd.TrajectoryCollection(gdf, 'trajectory_id', t='t')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "split = mpd.ObservationGapSplitter(traj_collection).split(gap=timedelta(minutes=15))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_defaults = {'linewidth':5, 'capstyle':'round', 'figsize':(9,3), 'legend':True}\n",
    "split.plot(column='trajectory_id', **plot_defaults)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## KalmanSmootherCV"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This smoother operates on the assumption of a nearly-constant velocity (CV) model. The `process_noise_std` and `measurement_noise_std` parameters can be used to tune the smoother:\n",
    "\n",
    "* `process_noise_std` governs the uncertainty associated with the adherence of the new (smooth) trajectories to the CV model assumption; higher values relax the assumption, therefore leading to less-smooth trajectories, and vice-versa.\n",
    "* `measurement_noise_std` controls the assumed error in the original trajectories; higher values dictate that the original trajectories are expected to be noisier (and therefore, less reliable), thus leading to smoother trajectories, and vice-versa.\n",
    "\n",
    "Try tuning these parameters and observe the resulting trajectories:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "help(mpd.KalmanSmootherCV)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "smooth = mpd.trajectory_smoother.KalmanSmootherCV(split).smooth(process_noise_std=0.1, measurement_noise_std=10)\n",
    "print(smooth)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hvplot_defaults = {'tiles':'CartoLight', 'frame_height':320, 'frame_width':320, 'cmap':'Viridis', 'colorbar':True}\n",
    "kwargs = {**hvplot_defaults, 'line_width':4}\n",
    "(split.hvplot(title='Original Trajectories', **kwargs) + \n",
    " smooth.hvplot(title='Smooth Trajectories', **kwargs))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "kwargs = {**hvplot_defaults, 'c':'speed', 'line_width':7, 'clim':(0,20)}\n",
    "(split.trajectories[2].hvplot(title='Original Trajectories', **kwargs) + \n",
    " smooth.trajectories[2].hvplot(title='Smooth Trajectories', **kwargs))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
